// map.js
import QQMap from '../../../utils/qqmap'
Page({
  data: {
    latitude: 30.59276,
    longitude: 114.30525,
    repairDetail: {},
    markers: [
      {
        id: 1,
        latitude: 30.595715298980824,
        longitude: 114.30722410583493,
        width: 24,
        height: 30
      },
      {
        id: 2,
        latitude: 30.593207000000003,
        longitude: 114.30602699999999,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40
      }
    ],
    polyline: []
  },
  onLoad ({id}) {
    this.getRepairDetail(id)
  },
  async getRepairDetail (id) {
    if (!id) return wx.utils.toast('参数有误！')
    const {code, data: repairDetail} = await wx.http.get('/repair/' + id)
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      repairDetail
    })
    this.getPolyline()
  },
  async getPolyline () {
    const {latitude, longitude} = await wx.getLocation()
    QQMap.search({
      keyword: this.data.repairDetail.houseInfo,
      location: [latitude, longitude].join(','),
      page_size: 1,
      success: (res) => {
        const markers = this.data.markers
        markers[0].latitude = res.data[0].location.lat
        markers[0].longitude = res.data[0].location.lng
        this.setData({
          markers
        })
        QQMap.direction({
          mode: 'bicycling',
          from: `${latitude},${longitude}`,
          to: `${res.data[0].location.lat},${res.data[0].location.lng}`,
          success: ({result}) => {
            const coors = result.routes[0].polyline
            const points = []
            //坐标解压（返回的点串坐标，通过前向差分进行压缩）
            for (let i = 2; i < coors.length; i++) {
              coors[i] = Number(coors[i - 2]) + Number(coors[i]) / 1000000;
            }
            for (let i = 0; i < coors.length; i += 2) {
              points.push({ latitude: coors[i], longitude: coors[i + 1] })
            }
            const markers = this.data.markers
            markers[1].latitude = points[Math.floor(points.length / 3)].latitude
            markers[1].longitude = points[Math.floor(points.length / 3)].longitude
            this.setData({
              markers
            })
            this.setData({
              latitude: points[0].latitude,
              longitude: points[0].longitude,
              polyline: [
                {
                  points,
                  color: '#5591af',
                  width: 4
                }
              ]
            })
          }
        })
      },
      fail: (err) => {
        console.log(err.message)
      }
    })
  },
  editRepair (ev) {
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id=' + ev.mark.id
    })
  },
  async cancelRepair (ev) {
    const {code} = await wx.http.put('/cancel/repaire/' + ev.mark.id)
    if (code !== 10000) return wx.utils.toast()
    wx.navigateTo({
      url: '/repair_pkg/pages/list/index'
    })
  }
})
